<script setup lang="ts">
import { ref, computed } from "vue";

const props = defineProps({
  // 图片列表
  urlList: {
    type: Array as () => string[],
    required: true
  },
  // 初始图片索引
  initialIndex: {
    type: Number,
    default: 0
  },
  // 图片放大是否需要压缩
  zoomCompressStr: {
    type: String,
    default: "?x-oss-process=style/jpg90"
  }
});

const imgVisible = ref(false);
const currentIndex = ref(0);
const openViewer = ref(false);
/**
 * 打开图片预览
 */
const openImagePreview = (url: string) => {
  const index = props.urlList.findIndex(item => item === url);
  currentIndex.value = index >= 0 ? index : 0;
  imgVisible.value = openViewer.value = true;
};
/**
 * 打开预览后图片压缩列表
 */
const compressUrlList = computed(() =>
  props.urlList.map(
    url => `${url}${props.zoomCompressStr ? props.zoomCompressStr : ""}`
  )
);
defineExpose({
  openImagePreview
});
</script>

<template>
  <div class="image-viewer p-[2px]">
    <!-- 图片列表展示 -->
    <div class="image__lazy">
      <img
        v-for="(url, index) in urlList"
        :key="url"
        v-lazy="`${url}?x-oss-process=image/resize,p_10,w_200,h_100`"
        :class="{ current: index === currentIndex && openViewer }"
        @click="openImagePreview(url)"
      />
    </div>

    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="imgVisible"
      :initialIndex="currentIndex"
      :url-list="compressUrlList"
      :zoom-rate="1.2"
      :max-scale="7"
      :min-scale="0.2"
      hide-on-click-modal
      @close="imgVisible = false"
      @switch="index => (currentIndex = index)"
    />
  </div>
</template>

<style lang="scss" scoped>
.image__lazy {
  img {
    width: 200px;
    height: 100px;
    margin-right: 5px;
    cursor: pointer;
    transition: box-shadow 0.2s ease-in-out;

    &.current {
      padding: 7px;
      background-color: var(--el-color-primary-light-6);
      border-radius: 3px;
      box-shadow: 0 0 0 2px var(--el-color-primary);
      transition: all 0.2s ease-in-out;
    }
  }
}
</style>
